package domain.service.event;

import core.util.ValidationUtil;
import domain.dao.event.EventImgInfoDao;
import domain.dao.event.OperatorInfoDao;
import domain.dao.event.TunnelEventInfoDao;
import domain.entity.event.EventImgInfo;
import domain.entity.event.EventOperatorInfo;
import domain.entity.event.TunnelEventInfo;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by bowen on 2017-08-17.
 */
@Service
public class TunnelEventInfoService {

    @Autowired
    private TunnelEventInfoDao eventInfoDao;
    @Autowired
    private OperatorInfoDao operatorInfoDao;
    @Autowired
    private EventImgInfoDao imgInfoDao;

    /**
     * 上传事件
     *
     * @param entity
     * @return
     */
    public void create(TunnelEventInfo entity) throws Exception {
        Map<String, Double> lngLat = geocoder(entity.getAddress());
        entity.setLat(lngLat.get("lat").toString());
        entity.setLng(lngLat.get("lng").toString());
        if (StringUtil.isNullOrEmpty(entity.getOperatorUsers())) entity.setType(true);
        eventInfoDao.create(entity);
        if(entity.getPid() > 0)  eventInfoDao.updateEventById(entity.getId());
        if (!StringUtil.isNullOrEmpty(entity.getOperatorUsers())) {
            String operator[] = entity.getOperatorUsers().split(",");
            List<EventOperatorInfo> operatorInfos = new ArrayList<EventOperatorInfo>();
            for (int i = 0; i < operator.length; i++) {
                EventOperatorInfo info = new EventOperatorInfo();
                info.setEventId(entity.getId());
                info.setRevertId(entity.getId());
                info.setUserId(operator[i]);
                operatorInfos.add(info);
            }
            operatorInfoDao.create(operatorInfos);
        }
        if (!StringUtil.isNullOrEmpty(entity.getImgs())) {
            String img[] = entity.getImgs().split(",");
            List<EventImgInfo> imgInfos = new ArrayList<EventImgInfo>();
            for (int i = 0; i < img.length; i++) {
                EventImgInfo info = new EventImgInfo();
                info.setEventId(entity.getId());
                info.setImg(img[i]);
                imgInfos.add(info);
            }
            imgInfoDao.create(imgInfos);
        }
    }

    /**
     * 我发起的事件
     *
     * @param createUser 发起人
     * @return
     */
    public List<TunnelEventInfo> getMyCreateEvents(String createUser) {
        return eventInfoDao.getMyCreateEvents(createUser);
    }

    /**
     * '@'我的事件
     *
     * @param operatorUser 发起人
     * @return
     */
    public List<TunnelEventInfo> getAtEvents(String operatorUser) {
        return eventInfoDao.getAtEvents(operatorUser);
    }

    /**
     * 公共事件
     *
     * @param
     * @return
     */
    public List<TunnelEventInfo> getPublicEvents() {
        return eventInfoDao.getPublicEvents();
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public TunnelEventInfo getEventById(long id) {
        return eventInfoDao.getEventById(id);
    }

    /**
     * 根据PID查询
     *
     * @param pid
     * @return
     */
    public TunnelEventInfo getEventByPid(long pid) {
        return eventInfoDao.getEventByPid(pid);
    }


    /**
     * 根据地址信息查询地址对应的经纬度
     *
     * @param address 地址
     * @return Map数据
     * @throws Exception
     */
    public static Map<String, Double> geocoder(String address) {
        Map<String, Double> resultMap = new HashMap<String, Double>();
        double lng = 0;
        double lat = 0;
        try {
            StringBuffer strBuffer = new StringBuffer("http://api.map.baidu.com/geocoder/v2/?");
            strBuffer.append("address=" + address);
            strBuffer.append("&output=json");
            strBuffer.append("&ak=" + ValidationUtil.baidu_ak);
            ClientRequest request = new ClientRequest(strBuffer.toString());
            ClientResponse<String> response = request.get();
            String strResult = "";
            if (response.getStatus() == 200) {
                strResult = response.getEntity(String.class);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsN = objectMapper.readTree(strResult);
                lng = jsN.findValue("lng").getDoubleValue();
                lat = jsN.findValue("lat").getDoubleValue();
            }
            resultMap.put("lng", lng);
            resultMap.put("lat", lat);
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    public List<TunnelEventInfo> getAllEvents() {
        return eventInfoDao.getAllEvents();
    }

    public int getTotalEvent(long eventId) {
        return eventInfoDao.getTotalEvent(eventId);
    }
}
